package com.alibaba.dubbo.job;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.governance.service.ProviderService;
import com.alibaba.dubbo.governance.service.RouteService;
import com.alibaba.dubbo.registry.common.domain.Route;
import com.alibaba.dubbo.registry.common.util.Tool;

public class GlobalRouteCreateJob {

	private static final Logger logger = LoggerFactory.getLogger(GlobalRouteCreateJob.class);

	@Autowired
	private RouteService routeService;

	@Autowired
	private ProviderService providerService;

	public void execute() {
		try {
			List<String> serviceList = Tool.sortSimpleName(new ArrayList<String>(providerService.findServices()));

			if (serviceList != null && !serviceList.isEmpty()) {
				List<Route> globalRoutes = routeService.findGlobalRoutesNoDuplicate();

				for (String service : serviceList) {
					try {
						checkService(service);

						for (Route route : globalRoutes) {
							try {
								List<Route> currentRouteList = routeService.findByService(service);
								route.setService(service);

								if (currentRouteList == null) {
									routeService.createRoute(route);
								} else if (!currentRouteList.contains(route)) {
									routeService.createRoute(route);
								}
							} catch (Exception e) {
							}
						}
					} catch (Exception e) {
					}
				}
			}
		} catch (Exception ex) {
			logger.error("GlobalRouteCreateJob execute error!");
		}
	}

	static void checkService(String service) {
		if (service.contains(","))
			throw new IllegalStateException("service(" + service + ") contain illegale ','");

		String interfaceName = service;
		int gi = interfaceName.indexOf("/");
		if (gi != -1)
			interfaceName = interfaceName.substring(gi + 1);
		int vi = interfaceName.indexOf(':');
		if (vi != -1)
			interfaceName = interfaceName.substring(0, vi);

		if (interfaceName.indexOf('*') != -1 && interfaceName.indexOf('*') != interfaceName.length() - 1) {
			throw new IllegalStateException("service(" + service + ") only allow 1 *, and must be last char!");
		}
	}
}
